package com.ask.interceptor;

import cn.hutool.core.util.StrUtil;
import com.ask.dto.UserDTO;
import com.ask.threadlocals.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

import static com.ask.constants.RedisConstant.LOGIN_USER_KEY;
import static com.ask.constants.RedisConstant.LOGIN_USER_TTL;

/**
 * token刷新拦截器
 * 对用户的令牌进行检查和刷新，以确保用户会话的持续性和安全性
 */

public class RefreshTokenInteceptor implements HandlerInterceptor {

    private RedisTemplate redisTemplate;

    public RefreshTokenInteceptor(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 从请求中获取令牌
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) // 令牌为空，放行
            return true;

        // 2. 根据令牌从redis中获取用户信息
        String tokenKey = LOGIN_USER_KEY + token;
        UserDTO user = (UserDTO) redisTemplate.opsForValue().get(tokenKey);
        if (user == null)
            return true;

        // 3. 将用户信息存储到threadLocal中
        UserHolder.setUser(user);

        // 4. 刷新令牌的有效期
        redisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        // 5. 返回true以继续处理请求
        return true;
    }
}
